#include "Sort.h"

void Swap(int* x, int* y)
{
	int tmp = *x;
	*x = *y;
	*y = tmp;
}

void PrintArray(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}

//插入排序
void InsertSort(int* a, int n)
{
;
	for (int i = 0; i < n - 1; i++)
	{
		int end = i;
		while (end >= 0)
		{
			if (a[end] > a[end + 1])
			{
				Swap(&a[end], &a[end + 1]);
			}
			else
				break;

			end--;
		}
	}
}

//希尔排序
void ShellSort(int* a, int n)
{

	int gap = n;
	while (gap > 1)
	{
		gap /= 2;

		for (int i = 0; i < n - gap; i++)
		{
			int end = i;
			while (end >= 0)
			{
				if (a[end] > a[end + gap])
				{
					Swap(&a[end], &a[end + gap]);
					end -= gap;
				}
				else
					break;
			}
		}
	}
}

//冒泡排序
void BubbleSort(int* a, int n)
{

	for (int i = 0; i < n - 1; i++)
	{
		int f = 0;
		for (int j = 0; j < n - i - 1; j++)
		{
			if (a[j] > a[j + 1])
			{
				Swap(&a[j], &a[j + 1]);
				f = 1;
			}
		}

		if (f == 0)
		{
			break;
		}
	}
}

//选择排序
void SelectSort(int* a, int n)
{

	int begin = 0;
	int end = n - 1;
	
	while (begin < end)
	{
		int maxi = begin;
		int mini = begin;
		for (int i = begin; i <= end; i++)
		{
			if (a[i] < a[mini])
				mini = i;
			if (a[i] > a[maxi])
				maxi = i;
		}
		Swap(&a[begin], &a[mini]);
		//防止最大的数在begin位置被换走
		if (maxi == begin)
			maxi = mini;

		Swap(&a[end], &a[maxi]);

		begin++;
		--end;
	}
}

//大堆的向下调整
void BigAdjustDown(int* a, int n,int parent)
{

	int child = parent * 2 + 1;
	
	while (child < n)
	{
		if (child + 1 < n && a[child] < a[child + 1])
		{
			++child;
		}

		if (a[parent] < a[child])
		{
			Swap(&a[parent], &a[child]);

			parent = child;
			child = parent * 2 + 1;
		}
		else
			break;
	}
}
//堆排序
void HeapSort(int* a, int n)
{

	for (int i = (n - 2) / 2; i >= 0; i--)
	{
		BigAdjustDown(a, n, i);
	}

	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		BigAdjustDown(a, end, 0);
		end--;
	}
}